﻿using GloboTicketAdmin.Mobile.Common;
using GloboTicketAdmin.Mobile.Models;
using GloboTicketAdmin.Mobile.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace GloboTicketAdmin.Mobile.Repositories
{
    public class CategoryRepository : ICategoryRepository
    {
        private readonly IHttpClientFactory _httpClientFactory;

        public CategoryRepository(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }


        public async Task<List<CategoryModel>> GetCategorys()
        {
            using HttpClient client = _httpClientFactory.CreateClient("GloboTicketAdminApiClient");
            try 
            {
                //List<CategoryModel>? categorys = await client.GetFromJsonAsync<List<CategoryModel>>(
                //    $"api/categorys",
                //    new JsonSerializerOptions(JsonSerializerDefaults.Web)
                //    );
                var options = new JsonSerializerOptions(JsonSerializerDefaults.Web)
                {
                    Converters = { new JsonStringEnumConverter() }, // 启用字符串与枚举的转换
                    PropertyNameCaseInsensitive = true // 忽略大小写（可选）
                };
                var response = await client.GetFromJsonAsync<ApiResponse<List<CategoryModel>>>($"api/categorys", options);
                return response != null ? response.Data : new List<CategoryModel>();
            }
            catch (Exception ex)
            {
                // Log the exception or handle it as needed
                return new List<CategoryModel>();
            }
        }

    }
}
